'use strict';

const Service = require('egg').Service;
const moment = require('moment');
const path = require('path');
const md5 = require("md5");
const fs = require('fs');
const qiniu = require('qiniu');
const sendToWormhole = require("stream-wormhole");
const bucket = 'jiniunai'; // 空间名
const imageUrl = 'img.olddriver.icu'; // 域名名称
const accessKey = 'nQNGIS0SdON_UwlkU2m5sFFG-y7sYMJ4tW85qL0H';
const secretKey = 'NmRTn983lrnlVeDAdMo18t3QJdoyPHByfcoztdna';
const mac = new qiniu.auth.digest.Mac(accessKey, secretKey);
const options = {
    scope: bucket,
    expires: 60 * 60
};
const putPolicy = new qiniu.rs.PutPolicy(options);
let config = new qiniu.conf.Config();
config.zone = qiniu.zone.Zone_z2;

class CommonService extends Service {
    async upload(type) {
        const { ctx } = this;
        const stream = await ctx.getFileStream();
        const filename =
            md5(stream.filename) + path.extname(stream.filename).toLocaleLowerCase();
        let uploadToken = await ctx.service.cache.get('qiniuyun-token');
        if (!uploadToken) {
            uploadToken = putPolicy.uploadToken(mac);
            await ctx.service.cache.set('qiniuyun-token', uploadToken, options.expires);
        }
        const formUploader = new qiniu.form_up.FormUploader(config)
        const putExtra = new qiniu.form_up.PutExtra()
        try {
            const data = await new Promise((resolve, reject) => {
                /*
                * formUploader 有好几种上传方法，
                * putStream 数据流上传
                * put 表单上传
                * putFile 指定本地文件上传
                * */
                formUploader.putStream(uploadToken, filename, stream, putExtra, function (respErr,
                    respBody, respInfo) {
                    if (respErr) {
                        return reject(respErr)
                    }
                    if (respInfo.statusCode === 200) {
                        resolve(respBody.key)
                    } else {
                        return reject(respBody)
                    }
                })
            })
            console.log('imgSrc', data)
            if (data !== "") {
                if (type === 'avatar') {
                    const userInfo = await ctx.service.cache.get(`profile_${ctx.user.userId}`);
                    await ctx.service.cache.set(`profile_${ctx.user.userId}`, { ...userInfo, avatar: `http://${imageUrl}/${data}` }, options.expires);
                }
                return {
                    message: 'ok',
                    status: 200,
                    result: {
                        url: `http://${imageUrl}/${data}`,
                        data
                    }
                };
            } else {
                return {
                    message: '系统异常，请稍后再试',
                    status: 501,
                    result: null
                };
            }
        } catch (err) {
            //如果出现错误，关闭管道
            await sendToWormhole(stream);
            return {
                message: '系统异常，请稍后再试',
                status: 501,
                result: null
            };
        }
    }
}

module.exports = CommonService;